# -*- coding: utf-8 -*-
from django.utils.safestring import mark_safe
from django.forms.widgets import HiddenInput

from .. import utils, settings

class Link(object):
    """
    Default widget for sorter field.
    """
    def __init__(self, label=None, name=None, value=None, direction=None):
        self.label = label
        self.name = name
        self.value = value
        self.direction = direction or settings.ASC
        self.querydict = None
                
    def get_arrow(self, direction):
        """
        Return a arrow char showing the order direction to end user.
        """
        arrow = {settings.ASC: u"▲", settings.DESC: u"▼"}[direction]
        return u"""%s&nbsp;""" % arrow
        
    def get_url(self, is_selected, is_reversed, is_default, name, value):
        querydict = self.querydict.copy()
        # the querydict key is deleted if:
        # - the field is the default one and it is not selected
        # - the field is the default one and is reversed
        if is_default and (not is_selected or is_reversed):
            return utils.url_without_key(name, querydict)
        # if the field is selected and not reversed i have to reverse the
        # value of the querydict
        if is_selected and not is_reversed:
            value = u"-%s" % value
        # return the url of the view that do sort
        querydict[name] = value
        return u"?%s" % querydict.urlencode()
        
    def render(self, is_selected, is_reversed, is_default, 
        label=None, name=None, value=None, direction=None):
        # passed values overrides instance ones
        label = self.label if label is None else label
        name = self.name if name is None else name
        value = self.value if value is None else value
        direction = self.direction if direction is None else direction
        
        # output
        template = u"""<span class="%s"><a href="%s">%s</a>%s%s</span>"""
        klass = (u"yasort", u"yasorted")[is_selected]
        arrow = self.get_arrow(direction) if is_selected else u""
        url = self.get_url(is_selected, is_reversed, is_default, name, value)
        # append an hidden input to mantain sorting after a form submit
        hidden = (u"", HiddenInput().render(name, value))[is_selected]

        return mark_safe(template % (klass, url, label, arrow, hidden))
